import { useRef, useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { Text, View } from "@tarojs/components";
import { useCreation, useUpdateEffect } from "ahooks";
import dayjs from "dayjs";

import ByRow from "@/components/ui/ByRow";
import Page from "@/components/common/Page";
import Card from "@/components/common/Card";
import ByCell from "@/components/ui/ByCell";
import ByIcon from "@/components/ui/ByIcon";
import ByText from "@/components/ui/ByText";
import Moment from "@/components/app/Moment";
import ByButton from "@/components/ui/ByButton";
import ByCellGroup from "@/components/ui/ByCellGroup";
import PageHeader from "@/components/common/PageHeader";
import PlanBaseSetting from "./components/PlanBaseSetting";
import PlanConstructionCard from "./components/PlanConstructionCard";

import ApiCrm from "@/api/crm";
import ApiWork from "@/api/work";
import useList from "@/hooks/useList";
import useFetch from "@/hooks/useFetch";
import useSubmit from "./utils/useSubmit";
import useGetTemplete from "./utils/useGetTemplete";
import useConstructionPlans from "./utils/usePlanList";
import useGetHolidayList from "@/hooks/useGetHolidayList";
import { getConstractDate, getPlanDate } from "./utils/tools";

import { ContractInfo } from "@/types/contract";
import { IntentCustomerData } from "@/types/customer";


export default () => {
  const { params } = useRouter();
  const requestParams = [{ intentCustomerId: Number(params.intentCustomerId) }];

  // 节假日: 秒级时间戳数组
  const [holidayUnixList] = useGetHolidayList();

  // 合同信息
  const { data: contractInfoData } = useFetch<ContractInfo>(
    ApiWork.getContractInfo,
    {
      defaultParams: requestParams,
      onAfter: (res) => res.contractInfo,
    }
  );

  // 客户信息
  const { data: customerData } = useFetch<IntentCustomerData>(
    ApiCrm.customerDetail,
    {
      defaultParams: requestParams,
      onAfter: (res) => res.intentCustomer,
    }
  );


  // 提交表单（存草稿  +  提交）
  const { loading, model, setModel, submit, submitAsDraft } = useSubmit(params);

  const { planStartDate, isSkipHoliday } = model;

  // 获取整个model信息
  const templateData = useGetTemplete(Number(params.intentCustomerId));
  useUpdateEffect(() => {
    setModel(templateData);
  }, [templateData]);


  // 是否已更新过
  const hadChanged = useRef(false)

  // 处理模板时间
  const { plans, initializePlans, deletePlan, updatePlanByIndex } =
    useConstructionPlans(
      templateData?.formConstructionPlanList,
      holidayUnixList,
      () => hadChanged.current = true
    );

  // 计算施工周期时间
  const planTimeView = useCreation(() => {
    return getPlanDate(plans, isSkipHoliday ? holidayUnixList : undefined);
  }, [plans, isSkipHoliday]);

  // 计算合同显示时间和周期
  const constractView = useCreation(() => {
    // plandBeginDate,
    const { contractDuration = 0 } = contractInfoData || {};
    return getConstractDate(
      model.planStartDate,
      contractDuration,
      holidayUnixList,
      isSkipHoliday
    );
  }, [planStartDate, contractInfoData, isSkipHoliday]);

  // 删除施工项
  async function beforeDeletePlan(index) {
    const { confirm } = await Taro.showModal({ title: "确认删除该项吗？" });
    if (confirm) deletePlan(index);
  }

  // 更新节假日状态和施工开始日期后，需要重新计算各阶段日期
  const handleContinue = (partialModel) => {
    setStep(1);
    initializePlans(partialModel.planStartDate, partialModel.isSkipHoliday);
    setModel(partialModel);
  };

  // 验证并保存
  async function handleSubmit() {
    // @ts-expect-error
    const index = plans.findIndex((e) => !e.executePostNames);

    // 1. 检查是否该填的数据是否都已填了
    if (index > -1) {
      const { constructionProjectName } = plans[index];
      Taro.showToast({
        icon: "none",
        title: `请补充${constructionProjectName}信息`,
      });

      Taro.pageScrollTo({
        offsetTop: -10,
        selector: "#item_" + index,
      });

      return;
    }

    // 计算最后的施工时间，是否超出合同日期
    if (dayjs(constractView!.end).diff(dayjs(planTimeView.end)) < 0) {
      Taro.showModal({
        title: "工期超期",
        content: "当前拟定工期超出合同工期,请调整阶段工期",
        showCancel: false,
        confirmText: "知道了",
      });

      return;
    }

    submit({
      planFinishDate: planTimeView.end,
      formConstructionPlanList: plans,
    });
  }

  const handleBack = async () => {
    if (hadChanged.current) {
      const { confirm } = await Taro.showModal({
        title: "退出拟定",
        content: "是否保存已编辑的内容，方便下次继续操作？",
        confirmText: "存草稿",
        cancelText: "直接返回",
      });

      if (confirm) {
        // 存草稿
        await submitAsDraft({
          planFinishDate: planTimeView.end,
          formConstructionPlanList: plans,
        });
      }
    }

    Taro.navigateBack({ delta: 1 });
  };

  // 切换步骤
  const [step, setStep] = useState<number>(0);

  // 获取工种列表
  const { list: workTypeList } = useList(ApiWork.getWorkTypeList);

  return (
    model.planStartDate && (
      <Page
        slotHeader={<PageHeader title="拟定" className="bg-page" onBack={handleBack} />}
        footerSticky
        slotFooter={
          step === 1 && (
            <ByButton
              size="large"
              className="w-2/3"
              loading={loading}
              onClick={handleSubmit}
            >
              保存
            </ByButton>
          )
        }
      >
        <View className="p-4">
          <Card className="mb-4">
            <ByRow content="between" align="center" className="font-bold">
              <Text>{customerData?.customerName}</Text>
              <Text className="text-primary">{customerData?.customerNo}</Text>
            </ByRow>

            <View className="mt-2 text-sm text-third">
              {customerData?.decorationFullAddress}
            </View>
          </Card>

          {step === 1 ? (
            <>
              <ByCellGroup className="mb-6">
                <ByCell size="small" label="合同工期:">
                  <Moment value={constractView?.start} type="month" />
                  <Text>~</Text>
                  <Moment value={constractView?.end} type="month" />
                  <Text>（{constractView?.duration}）</Text>
                  <Text>拟定</Text>
                  <ByText type="primary">
                    {constractView?.actualDuration}
                  </ByText>
                  <Text>工作日</Text>
                </ByCell>
                <ByCell
                  size="small"
                  label="施工工期:"
                  nextIcon={
                    <ByIcon
                      size={40}
                      name="Setting"
                      className="text-primary"
                      onClick={() => setStep(0)}
                    />
                  }
                >
                  <Moment value={planTimeView.start} type="month" />
                  <Text>~</Text>
                  <Moment value={planTimeView.end} type="month" />
                  <Text>（{planTimeView.duration}天）</Text>
                  <Text>拟定</Text>
                  <ByText type="primary">{planTimeView.actualDuration}</ByText>
                  <Text>{model.isSkipHoliday ? "工作日" : "自然日"}</Text>
                </ByCell>

                <ByCell
                  size="small"
                  label={`节假日${model.isSkipHoliday ? "不" : ""}施工`}
                >
                  {planTimeView.end ? ` 预计${planTimeView.end}完工` : ""}
                </ByCell>
              </ByCellGroup>

              {plans?.map((item, index) => (
                <View key={item.constructionPlanId} id={"item_" + index}>
                  <PlanConstructionCard
                    source={item}
                    workTypeList={workTypeList}
                    endDate={constractView?.endText}
                    startDate={constractView?.startText}
                    onChange={(e) => updatePlanByIndex(e as any)}
                    onDelete={() => beforeDeletePlan(index)}
                  />
                </View>
              ))}
            </>
          ) : (
            <PlanBaseSetting
              source={model}
              startDate={model?.plandBeginDate}
              onConfirm={handleContinue}
            />
          )}
        </View>
      </Page>
    )
  );
};
